package com.chare.Controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chare.pojo.*;
import com.chare.service.*;
import com.sun.deploy.net.URLEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shi
 * @since 2022-06-17
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService statusService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private INationService nationService;
    @Autowired
    private  IPositionService positionService;
    @Autowired
    private  IjobleveIService ijobleveIService;
    @GetMapping("/")
    @ApiModelProperty("查询所有员工")
    public RespPageBean getAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize,
                                Employee employee, LocalDateTime [] beginDateScope)

    {
                 return  employeeService.getEmployeeByPage(page,pageSize,employee,beginDateScope);
    }
    @ApiModelProperty("获得所有政治面貌")
    @GetMapping("/getAllPoliticsStatus")
    public List<PoliticsStatus> getAll()
    {
      return   statusService.list();
    }

    @ApiModelProperty("获得所有部门")
    @GetMapping("/getAllDeps")
    public List<Department> getAllDe()
    {
        return   departmentService.list();
    }
    @ApiModelProperty("获得所有民族")
    @GetMapping("/getAllNations")
    public List<Nation> getAllNa()
    {
        return   nationService.list();
    }
    @ApiModelProperty("获得所有职位")
    @GetMapping("/getAllPositions")
    public List<Position> getAllPo()
    {
        return   positionService.list();
    }
    @ApiModelProperty("获得所有职称登记")
    @GetMapping("/getAllJoblevels")
    public List<Joblevel> getAlljo()
    {
        return   ijobleveIService.list();
    }
    @ApiOperation(value = "获取工号")
    @GetMapping("/maxWorkId")
    public RespBean maxWorkID()
    {
        return employeeService.maxWorkId();
    }
@ApiModelProperty(value = "添加员工")
    @PostMapping("/")
    public  RespBean addEmp(@RequestBody Employee employee)
{
  return employeeService.insertEm(employee);
}
@ApiModelProperty(value = "删除员工")
    @DeleteMapping("/deleteEmployee/{id}")
    public RespBean deleteEm(@PathVariable Integer id)
{
    if(employeeService.removeById(id))
    {
        return RespBean.success("删除成功");
    }
    return RespBean.success("删除失败");
}
@ApiModelProperty("更新员工")
    @PutMapping("/updateEmployee")
    public  RespBean updateEm(@RequestBody Employee employee)
{
    if(employeeService.updateById(employee))

    {
        return RespBean.success("更新成功");
    }
    return RespBean.success("更新失败");
}
    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void   exportEmployee(HttpServletResponse response)
    {
        List<Employee> list = employeeService.getEmployee(null);
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook book = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream out = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls","UTF-8"));
            out = response.getOutputStream();
            book.write(out);
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
    }
    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public  RespBean importEmployee(MultipartFile multipartFile)
    {
        //查询所有民族
      List<Nation> naetions=  nationService.list();
      //查询所有政治面貌
       List<PoliticsStatus> politicsStatuses= statusService.list();
       //查询所有职位
        List<Position> positions=positionService.list();
        //查询所有部门
        List<Department> departments=departmentService.list();
        //查询所有职称
        List<Joblevel> joblevels=ijobleveIService.list();
        ImportParams importParams=new ImportParams();
        //去除标题
        importParams.setTitleRows(1);
        try {
          List<Employee> list=  ExcelImportUtil.importExcel( multipartFile.getInputStream(),Employee.class,importParams);
          list.forEach(employee->{
              employee.setNationId( naetions.get( naetions.indexOf(  new Nation(employee.getNation().getName()))).getId());
              employee.setPosId(politicsStatuses.get(politicsStatuses.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
              employee.setPoliticId(positions.get(positions.indexOf(new Position(employee.getPosition().getName()))).getId());
              employee.setDepartmentId(departments.get(departments.indexOf(new Department(employee.getDepartment().getName()))).getId());
              employee.setJobLevelId(joblevels.get(joblevels.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());

          });
            if(employeeService.saveBatch(list))
            {
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }
}
